package com.hliushi.bookmanager.config;

import com.hliushi.bookmanager.mapper.ReaderMapper;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(urlPatterns = {"/", "/index", "/admin/*", "/user/*", "/toChPwdPage"})
public class SessionFilter implements Filter {

    private ReaderMapper readerMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext servletContext = filterConfig.getServletContext();
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        readerMapper = (ReaderMapper) ctx.getBean("readerMapper");

    }


    /**
     * 过滤器的逻辑代码
     *
     * @param servletRequest  请求
     * @param servletResponse 响应
     * @param filterChain     提供对该过滤器链中下一个过滤器的访问
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpSession session = request.getSession();

        if (session.getAttribute("name") == null) {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = ((UserDetails) principal).getUsername();
            String name = "管理员";
            // 这里管理员的username写死了,就是名称为admin. 如果想添加多个管理员,需要定义一个集合,放着管理员的名称
            if (!username.equals("admin")) {
                name = readerMapper.getReaderName(username);
            }
            // session.setAttribute("readerId",);
            session.setAttribute("name", name);
            session.setAttribute("username", username);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

}
